import { defineStore } from 'pinia';
import { inject, provide, ref } from 'vue';

// API响应类型定义
interface ProductCheckResponse {
  exists: boolean;
  click_url?: string;
  status: string;
}
// 在文件顶部的接口定义区域添加
interface H5PaymentResponse {
  order_id: string;
  status: string;
  amount: number;
  // 可以根据实际响应数据添加其他字段
}

interface PaymentResponse {
  order_id: string;
  payment_params: {
    appId: string;
    nonceStr: string;
    package: string;
    signType: string;
    paySign: string;
    timeStamp: string;
  };
}

// Add new interface for order status
interface OrderStatusResponse {
  status: 'paid' | 'unpaid' | 'cancelled';
  click_url?: string;
}

interface Product {
  id: string;
  product_id: number;
  name: string;
  title: string;
  description: string;
  image_url: string;
  is_purchased: boolean;
  price: number;
  click_url?: string;
  version: string;
  category: number
  created_at: string
  duration_days: number
  is_available: boolean
  opening: string
  updated_at: string
}

// 定义支付实例的类型
interface UniPay {
  createOrder: (params: {
    provider: string;
    total_fee: number;
    description: string;
    order_no: string;
    out_trade_no: string;
    type: string;
  }) => Promise<any>;
}

// Add wx namespace declaration for TypeScript
declare const wx: {
  requestPayment: (params: {
    appId: string;
    timeStamp: string;
    nonceStr: string;
    package: string;
    signType: string;
    paySign: string;
  }) => Promise<{ errMsg: string }>;
};

export const useProductStore = defineStore('product', () => {
  const agents = ref<Product[]>([]);
  const loading = ref(false);
  const checkData = ref({})
  const currentQrcode = ref('');
  // 注入支付实例
  const payInstance = inject<UniPay>('uniPay');
  // 获取产品列表
  async function fetchAgents() {
    loading.value = true;
    console.log('[关键节点] 开始加载商品数据');
    try {
      const res = await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/products/',
        method: 'GET',
        header: {
          // 'Authorization': `Bearer ${uni.getStorageSync('userInfo')?.access_token}`
        }
      });
      // console.log(res, '+++++++21212111111');
      if (res.statusCode === 200 && Array.isArray(res.data)) {
        console.log('[商品数据]', res.data);
        agents.value = res.data.map(product => (
          {
            ...product,
            id: product.product_id,
            image_url: product.image_url || 'https://images.unsplash.com/photo-1620712943543-bcc4688e7485?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80',
            is_purchased: false
          }
        ));
        // 检查购买状态
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo?.access_token && userInfo?.phone) {
          await Promise.all(agents.value.map(async (item) => {
            try {
              const checkRes = await uni.request({
                url: `https://52d47b77.r34.cpolar.top/api/product-check/?product_id=${item.id}&phone=${userInfo.phone}`,
                method: 'GET',
                header: {
                  'Authorization': `Bearer ${userInfo.access_token}`
                }
              });
              console.log(checkRes, '--------21212111111');
              if (checkRes.statusCode === 200) {
                const checkData = checkRes.data as ProductCheckResponse;
                item.is_purchased = checkData.exists || false;
              }
            } catch (err) {
              console.error('检查购买状态失败:', err);
            }
          }));
        }
      }
    } catch (error) {
      console.error('[错误] 加载商品失败:', error);
      uni.showToast({
        title: '获取商品列表失败',
        icon: 'none'
      });
    } finally {
      loading.value = false;
    }
  }

  // 检查订单状态
  async function checkOrderStatus(orderId: string, userInfo: any): Promise<OrderStatusResponse> {
    try {
      const res = await uni.request({
        url: `https://52d47b77.r34.cpolar.top/api/payments/quick-update/${orderId}/`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${userInfo.access_token}`,
          'Content-Type': 'application/json'
        }
      });
      console.log(res, '!!!!!111111555');
      if (res.statusCode === 401) {
        uni.removeStorageSync('userInfo');
        throw new Error('登录过期');
      }

      if (res.statusCode === 200) {
        return res.data as OrderStatusResponse;
      }

      throw new Error('获取订单状态失败');
    } catch (error) {
      console.error('检查订单状态失败:', error);
      throw error;
    }
  }

  // 创建用户商品记录
  async function createUserProduct(productId: number, userInfo: any) {
    try {
      // 计算过期时间（当前时间 + 30天）
      const expireDate = new Date();
      expireDate.setDate(expireDate.getDate() + 30);

      console.log('创建用户商品记录，参数:', {
        product_id: productId,
        phone: userInfo.phone,
        expire_time: expireDate.toISOString(),
        duration: 30
      });

      await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/user-products/',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${userInfo.access_token}`,
          'content-type': 'application/json'
        },
        data: {
          product_id: productId,
          phone: userInfo.phone,
          expire_time: expireDate.toISOString(),
          duration: 30
        }
      });

      // console.log('创建用户商品记录响应:', res);

      // if (res.statusCode === 500) {
      //   console.error('服务器错误:', res.data);
      //   throw new Error('服务器错误，请稍后重试');
      // }

      // if (res.statusCode !== 201) {
      //   console.error('创建用户商品记录失败:', res);
      //   throw new Error(`创建用户商品记录失败: ${JSON.stringify(res.data)}`);
      // }

      // return res.data;
    } catch (error) {
      console.error('创建用户商品记录失败:', error);
      throw error;
    }
  }

  // 生成支付二维码
  async function generatePaymentQRCode(item: Product) {
    try {
      uni.showLoading({ title: '处理中...' });
      console.log('开始生成支付订单，商品信息:', item);

      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo?.access_token) {
        throw new Error('用户未登录');
      }

      if (!userInfo?.phone) {
        throw new Error('请先绑定手机号');
      }

      if (!item.product_id && !item.id) {
        throw new Error('商品ID不能为空');
      }
      // #ifdef MP-WEIXIN
      const requestData = {
        product_id: item.product_id || item.id,
        phone: userInfo.phone,
        openid: userInfo.openid || '',
        amount: item.price || 0,
        title: item.name || item.title || '商品购买'
      };

      console.log('支付请求数据:', requestData);

      const qrcodeRes = await uni.request({
        url: 'https://52d47b77.r34.cpolar.top/api/payments/',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${userInfo.access_token}`,
          'content-type': 'application/json'
        },
        data: {
          product_id: item.product_id || item.id,
          phone: userInfo.phone,
          openid: userInfo.openid || '',
          total_fee: item.price * 100
        }
      });

      console.log('支付接口响应:', qrcodeRes);

      if (qrcodeRes.statusCode !== 200) {
        throw new Error(`服务器响应错误: ${qrcodeRes.statusCode}, ${JSON.stringify(qrcodeRes.data)}`);
      }

      const paymentData = qrcodeRes.data as PaymentResponse;
      try {
        uni.showLoading({ title: '处理支付中...' });

        // 验证支付参数完整性
        const requiredParams = ['timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
        const missingParams = requiredParams.filter(p => !paymentData.payment_params[p as keyof typeof paymentData.payment_params]);

        if (missingParams.length > 0) {
          throw new Error(`支付参数不完整: 缺少 ${missingParams.join(', ')}`);
        }

        const res = await wx.requestPayment({
          ...paymentData.payment_params
        });

        if (res.errMsg === 'requestPayment:ok') {
          console.log('支付成功');

          // 调用快速更新API
          await uni.request({
            url: `https://52d47b77.r34.cpolar.top/api/payments/quick-update/${paymentData.order_id}/`,
            method: 'POST',
            header: {
              'Authorization': `Bearer ${userInfo.access_token}`,
              'Content-Type': 'application/json'
            }
          });

          // 创建用户商品记录
          const productId = Number(item.id || item.product_id);
          if (isNaN(productId)) {
            throw new Error('无效的商品ID');
          }
          await createUserProduct(productId, userInfo);

          // 刷新商品列表
          await fetchAgents();

          uni.showToast({
            title: '支付成功',
            icon: 'success'
          });

          // 如果商品有跳转链接，延迟跳转
          // if (item.click_url) {
          //   setTimeout(() => {
          //     uni.navigateTo({
          //       url: `/pages/AIChat/AiChat?click_url=${encodeURIComponent(item.click_url!)}`
          //     });
          //   }, 1500);
          // }
        }

      } catch (error: any) {
        console.error('支付处理失败:', error);
        let errorMsg = '支付失败，请重试';

        if (error.message?.includes('登录过期')) {
          errorMsg = '登录已过期，请重新登录';
        } else if (error.message?.includes('ORDERPAID')) {
          errorMsg = '订单已支付，请勿重复操作';
          await fetchAgents(); // 自动刷新状态
        } else if (error.message?.includes('支付参数不完整')) {
          errorMsg = '支付参数错误，请联系客服';
        }

        uni.showToast({
          title: errorMsg,
          icon: 'none'
        });
        throw error;
      } finally {
        uni.hideLoading();
      }
      // #endif
      // #ifdef H5
      try {
        // 1. 创建订单
        const orderRes = await uni.request({
          url: 'https://52d47b77.r34.cpolar.top/api/payments/',
          method: 'POST',
          header: {
            'Authorization': `Bearer ${userInfo.access_token}`,
            'content-type': 'application/json'
          },
          data: {
            product_id: item.product_id || item.id,
            phone: userInfo.phone,
            id: userInfo.id
          }
        });

        console.log('H5支付订单创建响应:', orderRes);

        if (orderRes.statusCode !== 200) {
          throw new Error('创建支付订单失败');
        }

        const orderInfo = orderRes.data as H5PaymentResponse;
        const payInstance = inject<UniPay>('uniPay');

        if (!payInstance) {
          throw new Error('支付组件未初始化');
        }

        // 2. 发起支付
        const payResult = await payInstance.createOrder({
          provider: 'wxpay',
          total_fee: item.price * 100, // 转换为分
          description: item.name,
          order_no: orderInfo.order_id,
          out_trade_no: `${orderInfo.order_id}-${Date.now()}`,
          type: 'h5' // H5支付类型
        });

        console.log('H5支付发起结果:', payResult);

        if (payResult.errCode === 0) {
          if (payResult.order?.h5_url) {
            // 跳转到支付页面
            window.location.href = payResult.order.h5_url;
          } else {
            throw new Error('获取支付链接失败');
          }
        } else {
          throw new Error(payResult.errMsg || '支付初始化失败');
        }

      } catch (error: any) {
        console.error('H5支付处理失败:', error);
        throw error;
      }
      // #endif
    } catch (error: any) {
      console.error('生成订单二维码失败:', {
        error: error.message,
        stack: error.stack,
        requestInfo: {
          url: 'https://52d47b77.r34.cpolar.top/api/payments/',
          method: 'POST',
          productInfo: item
        }
      });

      let errorMessage = '生成订单二维码失败';
      if (error.message.includes('用户未登录')) {
        // #ifdef MP-WEIXIN
        uni.navigateTo({
          url: '/pages/login/login'
        })
        // #endif
        // #ifdef H5
        uni.navigateTo({
          url: '/pages/login/phone'
        })
        // #endif
        errorMessage = '请先登录';
      } else if (error.message.includes('请先绑定手机号')) {
        errorMessage = '请先绑定手机号';
      } else if (error.message.includes('商品ID不能为空')) {
        errorMessage = '商品信息无效';
      } else if (error.message.includes('服务器响应错误')) {
        errorMessage = '服务器响应错误，请稍后重试';
      }

      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      });

      throw error;
    }
  }

  // 处理购买流程
  async function handleBuy(productId: string) {
    try {
      const product = agents.value.find(item => item.id === productId);
      if (!product) {
        throw new Error('商品不存在');
      }

      // 检查用户是否已购买
      if (product.is_purchased) {
        uni.showToast({
          title: '您已购买过此商品',
          icon: 'none'
        });
        return;
      }

      // 检查用户登录状态
      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo?.access_token) {
        // #ifdef MP-WEIXIN
        uni.navigateTo({
          url: '/pages/login/login'
        });
        // #endif
        // #ifdef H5
        uni.navigateTo({
          url: '/pages/login/phone'
        });
        // #endif
        return;
      }

      // 检查手机号绑定
      if (!userInfo?.phone) {
        uni.showToast({
          title: '请先绑定手机号',
          icon: 'none'
        });
        return;
      }

      // 统一调用支付流程
      await generatePaymentQRCode(product);

    } catch (error: any) {
      // console.error('购买处理失败:', error);
      uni.showToast({
        title: '购买失败，请重试',
        icon: 'none'
      });
    }
  }

  return {
    agents,
    loading,
    currentQrcode,
    fetchAgents,
    generatePaymentQRCode,
    handleBuy
  };
});
